/**
 * 快递员管理 - 主界面
 */
Ext.define("PSI.Express.ExpressMan.MainForm", {
	extend : "Ext.panel.Panel",
	border : 0,
	layout : "border",

	/**
	 * 初始化组件
	 */
	initComponent : function() {
		var me = this;

		Ext.apply(me, {
					tbar : me.getToolbarCmp(),
					items : [{
								region : "north",
								height : 60,
								layout : "fit",
								border : 0,
								title : "查询条件",
								collapsible : true,
								layout : {
									type : "table",
									columns : 4
								},
								items : me.getQueryCmp()
							}, {
								region : "center",
								layout : "border",
								border : 0,
								items : [{
											region : "center",
											layout : "fit",
											items : [me.getMainGrid()]
										}, {
											region : "east",
											layout : "fit",
											width : "30%",
											split : true,
											items : [me.getDetailGrid()]
										}]
							}]
				});

		me.callParent(arguments);

		me.editQueryName = Ext.getCmp("editQueryName");
		me.editQueryMobile = Ext.getCmp("editQueryMobile");
		me.editQueryStatus = Ext.getCmp("editQueryStatus");

		me.onQuery();
	},

	getToolbarCmp : function() {
		var me = this;

		return [{
					text : "新增快递员",
					iconCls : "PSI-button-add",
					handler : me.onAddExpressMan,
					scope : me
				}, "-", {
					text : "编辑快递员",
					iconCls : "PSI-button-edit",
					handler : me.onEditExpressMan,
					scope : me
				}, "-", {
					text : "删除快递员",
					iconCls : "PSI-button-delete",
					handler : me.onDeleteExpressMan,
					scope : me
				}, "-", {
					text : "刷新",
					iconCls : "PSI-button-refresh",
					handler : me.onQuery,
					scope : me
				}, "-", {
					text : "关闭",
					iconCls : "PSI-button-exit",
					handler : function() {
						location.replace(PSI.Const.BASE_URL);
					}
				}];
	},

	onAddExpressMan : function() {
		var me = this;

		var form = Ext.create("PSI.Express.ExpressMan.EditForm", {
					parentForm : me
				});
		form.show();
	},

	onEditExpressMan : function() {
		var me = this;
		var item = me.getMainGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			PSI.MsgBox.showInfo("请选择要编辑的快递员");
			return;
		}
		var man = item[0];

		var form = Ext.create("PSI.Express.ExpressMan.EditForm", {
					parentForm : me,
					entity : man
				});
		form.show();
	},

	onDeleteExpressMan : function() {
		var me = this;
		var item = me.getMainGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			PSI.MsgBox.showInfo("请选择要删除的快递员");
			return;
		}

		var man = item[0];

		var store = me.getMainGrid().getStore();
		var index = store.findExact("id", man.get("id"));
		index--;
		var preIndex = null;
		var preItem = store.getAt(index);
		if (preItem) {
			preIndex = preItem.get("id");
		}

		var info = "请确认是否删除快递员: <span style='color:red'>" + man.get("name")
				+ "</span>";

		var funcConfirm = function() {
			var el = Ext.getBody();
			el.mask("正在删除中...");

			var r = {
				url : PSI.Const.BASE_URL + "Home/Express/deleteExpressMan",
				method : "POST",
				params : {
					id : man.get("id")
				},
				callback : function(options, success, response) {
					el.unmask();

					if (success) {
						var data = Ext.JSON.decode(response.responseText);
						if (data.success) {
							PSI.MsgBox.tip("成功完成删除操作");
							me.refreshEditResult(preIndex);
						} else {
							PSI.MsgBox.showInfo(data.msg);
						}
					} else {
						PSI.MsgBox.showInfo("网络错误");
					}
				}
			};

			Ext.Ajax.request(r);
		};

		PSI.MsgBox.confirm(info, funcConfirm);
	},

	getMainGrid : function() {
		var me = this;
		if (me.__mainGrid) {
			return me.__mainGrid;
		}

		var modelName = "PSIExpressMan";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "name", "mobile", "district", "wxId",
							"bindCode", "status"]
				});

		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : [],
					pageSize : 20,
					proxy : {
						type : "ajax",
						actionMethods : {
							read : "POST"
						},
						url : PSI.Const.BASE_URL
								+ "Home/Express/expressManList",
						reader : {
							root : 'dataList',
							totalProperty : 'totalCount'
						}
					}
				});
		store.on("beforeload", function() {
					store.proxy.extraParams = me.getQueryParam();
				});
		store.on("load", function(e, records, successful) {
					if (successful) {
						me.gotoMainGridRecord(me.__lastId);
					}
				});

		me.__mainGrid = Ext.create("Ext.grid.Panel", {
					title : "快递员",
					border : 0,
					viewConfig : {
						enableTextSelection : true
					},
					columnLines : true,
					columns : [{
								header : "姓名",
								dataIndex : "name",
								menuDisabled : true,
								sortable : false
							}, {
								header : "手机号",
								dataIndex : "mobile",
								menuDisabled : true,
								sortable : false
							}, {
								header : "所属片区",
								dataIndex : "district",
								menuDisabled : true,
								sortable : false,
								width : 400
							}, {
								header : "微信ID",
								dataIndex : "wxId",
								menuDisabled : true,
								sortable : false
							}, {
								header : "绑定微信验证码",
								dataIndex : "bindCode",
								menuDisabled : true,
								sortable : false
							}, {
								header : "状态",
								dataIndex : "status",
								menuDisabled : true,
								sortable : false,
								width : 60,
								renderer : function(value) {
									return value == 0
											? "<span style='color:red'>停用</span>"
											: "启用";
								}
							}],
					store : store,
					bbar : [{
								id : "pagingToobar",
								xtype : "pagingtoolbar",
								border : 0,
								store : store
							}, "-", {
								xtype : "displayfield",
								value : "每页显示"
							}, {
								id : "comboCountPerPage",
								xtype : "combobox",
								editable : false,
								width : 60,
								store : Ext.create("Ext.data.ArrayStore", {
											fields : ["text"],
											data : [["20"], ["50"], ["100"],
													["300"], ["1000"]]
										}),
								value : 20,
								listeners : {
									change : {
										fn : function() {
											store.pageSize = Ext
													.getCmp("comboCountPerPage")
													.getValue();
											store.currentPage = 1;
											Ext.getCmp("pagingToobar")
													.doRefresh();
										},
										scope : me
									}
								}
							}, {
								xtype : "displayfield",
								value : "条记录"
							}],
					listeners : {
						itemdblclick : {
							fn : me.onEditExpressMan,
							scope : me
						},
						select : {
							fn : me.onMainGridSelect,
							scope : me
						}
					}
				});

		return me.__mainGrid;
	},

	/**
	 * 查询条件
	 */
	getQueryCmp : function() {
		var me = this;
		return [{
					id : "editQueryName",
					labelWidth : 60,
					labelAlign : "right",
					labelSeparator : "",
					fieldLabel : "姓名",
					margin : "5, 0, 0, 0",
					xtype : "textfield"
				}, {
					id : "editQueryMobile",
					labelWidth : 60,
					labelAlign : "right",
					labelSeparator : "",
					fieldLabel : "手机号",
					margin : "5, 0, 0, 0",
					xtype : "textfield"
				}, {
					id : "editQueryStatus",
					xtype : "combo",
					queryMode : "local",
					editable : false,
					valueField : "id",
					labelWidth : 60,
					labelAlign : "right",
					labelSeparator : "",
					fieldLabel : "状态",
					margin : "5, 0, 0, 0",
					store : Ext.create("Ext.data.ArrayStore", {
								fields : ["id", "text"],
								data : [[-1, "全部"], [1, "启用"], [0, "停用"]]
							}),
					value : 1
				}, {
					xtype : "container",
					items : [{
								xtype : "button",
								text : "查询",
								width : 100,
								margin : "5 0 0 10",
								iconCls : "PSI-button-refresh",
								handler : me.onQuery,
								scope : me
							}, {
								xtype : "button",
								text : "清空查询条件",
								width : 100,
								margin : "5, 0, 0, 10",
								handler : me.onClearQuery,
								scope : me
							}]
				}];
	},

	/**
	 * 查询
	 */
	onQuery : function() {
		var me = this;
		me.getMainGrid().getStore().removeAll();
		me.getDetailGrid().getStore().removeAll();

		Ext.getCmp("pagingToobar").doRefresh();
	},

	/**
	 * 清除查询条件
	 */
	onClearQuery : function() {
		var me = this;

		me.editQueryName.setValue(null);
		me.editQueryMobile.setValue(null);

		me.onQuery();
	},

	getQueryParam : function() {
		var me = this;

		var result = {};

		var name = me.editQueryName.getValue();
		if (name) {
			result.name = name;
		}

		var mobile = me.editQueryMobile.getValue();
		if (mobile) {
			result.mobile = mobile;
		}

		result.status = me.editQueryStatus.getValue();

		return result;
	},

	onMainGridSelect : function() {
		var me = this;
		me.getDetailGrid().setTitle("所属片区");
		var item = me.getMainGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}

		me.refreshDetailGrid();
	},

	getDetailGrid : function() {
		var me = this;
		if (me.__detailGrid) {
			return me.__detailGrid;
		}

		var modelName = "PSIExpressManDistrict";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["name"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__detailGrid = Ext.create("Ext.grid.Panel", {
					title : "所属片区",
					viewConfig : {
						enableTextSelection : true
					},
					columnLines : true,
					columns : [{
								header : "片区",
								dataIndex : "name",
								menuDisabled : true,
								sortable : false,
								flex : 1
							}],
					store : store
				});

		return me.__detailGrid;
	},

	refreshDetailGrid : function() {
		var me = this;
		var item = me.getMainGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}
		var man = item[0];

		var grid = me.getDetailGrid();
		var el = grid.getEl();
		el.mask(PSI.Const.LOADING);

		var r = {
			url : PSI.Const.BASE_URL + "Home/Express/expressManDistrict",
			params : {
				id : man.get("id")
			},
			method : "POST",
			callback : function(options, success, response) {
				var store = grid.getStore();

				store.removeAll();

				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					store.add(data);
				}

				el.unmask();
			}
		};
		Ext.Ajax.request(r);
	},

	gotoMainGridRecord : function(id) {
		var me = this;
		var grid = me.getMainGrid();
		var store = grid.getStore();
		if (id) {
			var r = store.findExact("id", id);
			if (r != -1) {
				grid.getSelectionModel().select(r);
			} else {
				grid.getSelectionModel().select(0);
			}
		}
	},

	refreshEditResult : function(id) {
		var me = this;
		me.__lastId = id;
		me.onQuery();
	}
});